import os
import yaml
import fastdeploy as fd
import logging


from VideoProcessor import VideoProcessor
import AudioUtils
import FrameSR
from PyQt5.QtCore import QThread, pyqtSignal


# 设置日志
def set_log():
    log_file = 'run.log'
    log_format = '%(asctime)s - %(levelname)s - %(funcName)s - %(message)s'
    logging.basicConfig(filename=log_file, filemode='w', format=log_format, level=logging.INFO)
    logging.info('start run')


class MainThread(QThread):
    signal = pyqtSignal(str)

    def __init__(self,input_path,output_path,model_name,use_gpu):
        super().__init__()
        self.running = False
        self.video_path = input_path
        self.output_path = output_path
        self.model_name = model_name
        self.use_gpu = use_gpu

    def run(self):
        self.running = True
        frame_count = 50  # 每个临时视频帧数
        set_log()
        with open('configure.yml', 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)

        temp_path = config['TempPath']
        audio_path = config['AudioPath']
        model_path = config['ModelPath']

        # 提取音频
        isExtract = AudioUtils.extract_audio(self.video_path, 'music.mp3', output_dir=audio_path)

        # 视频分帧 调整大小为320x180 然后合并成一个中间视频
        vpc = VideoProcessor(video_path=self.video_path, temp_path=temp_path, frame_count=frame_count)
        vpc.processing()

        # 模型加载  判断是否使用 gpu
        option = fd.RuntimeOption()
        if self.use_gpu: option.use_gpu()
        model = FrameSR.FastSR(model_path=model_path, model_name=self.model_name, runtime_option=option)

        # 超分视频
        FrameSR.SR_Video(model, self.output_path, self.signal)
        os.remove('temp.mp4')

        # 音频合并
        if isExtract:
            output_file = os.path.join(self.output_path, 'output.mp4')
            audio_file = os.path.join(audio_path, 'music.mp3')
            product_file = os.path.join(self.output_path, 'end.mp4')
            AudioUtils.merge_audio(output_file, audio_file, product_file)

        self.signal.emit("finished")